import {
  TOGGLE_TYPE,
  ADD_CURRENT_LIST,
  TOGGLE_CURRENT_INDEX,
  CHANGE_LIST,
  TOGGLE_MUSIC,
  TOGGLE_RANDOM_MUSIC,
  TOGGLE_LOOP
} from "./types";

import { getSongUrl } from "./service";

export default {
  namespaced: true,
  moduleName: "player",
  state() {
    return {
      playerType: "mini", // full 全屏  small mimi播放器
      currentIdx: -1, // 当前播放歌曲的下标
      currentList: [], //  当前播放的歌单
      loop: 3, // 1单曲循环 2列表循环 3随机循环
    };
  },
  getters: {
    currentSong(state) {
      const { currentList, currentIdx } = state;
      if (!currentList.length) return {};
      return currentList[currentIdx];
    },
  },
  mutations: {
    // 切换大小屏幕
    [TOGGLE_TYPE](state, payload) {
      state.playerType = payload;
    },
    // 保存歌单信息
    [ADD_CURRENT_LIST](state, payload) {
      state.currentList = payload;
    },
    // 更改播放歌曲下标
    [TOGGLE_CURRENT_INDEX](state, payload) {
      state.currentIdx = payload;
    },
    [TOGGLE_LOOP](state) {
      state.loop = state.loop === 3 ? 1 : state.loop +=1

    }
  },
  actions: {
    async [CHANGE_LIST]({ commit }, payload) {
      const { list, idx } = payload;
      // 给list增加url的方法
      const mids = list.map((item) => item.mid);
      const { err, urls } = (await getSongUrl(mids)) || [];
      if (err) return;
      const newlist = list.map((item, index) => {
        return {
          ...item,
          songUrl: urls[index],
        };
      });
      commit(TOGGLE_TYPE, "full");
      commit(ADD_CURRENT_LIST, newlist);
      commit(TOGGLE_CURRENT_INDEX, idx);
    },
    // 切换歌曲
    [TOGGLE_MUSIC]({ commit, state }, payload) {
      const { currentIdx, currentList } = state;
      let index = currentIdx;
      const max = currentList.length - 1;
      if (payload === "prev") {
        // 向前
        index = index > 0 ? (index -= 1) : max;
      } else {
        // 向后
        index = index < max ? (index += 1) : 0;
      }
      commit(TOGGLE_CURRENT_INDEX, index);
    },
    // 随机歌曲
    [TOGGLE_RANDOM_MUSIC]({ commit, state }) {
      const {currentList } = state;
      const index = parseInt(Math.random()*(currentList.length),10)
      commit(TOGGLE_CURRENT_INDEX, index);
    },
  },
};
